__author__ = 'l4537'
#coding:utf-8
import telnetlib,time,re,sys,getpass,pexpect


def Telnet(ip,user,password,commands):
    try:
        tn = telnetlib.Telnet(ip)
    except Exception as e:
        print("IP 地址连接错误")
    tn.read_until(b"login:",timeout=5)
    tn.write(user.encode('ascii') + b"\n")
    if password:
        tn.read_until(b"Password: ",timeout=5)
        tn.write(password.encode('ascii') + b"\n")
    tn.read_some()
    result = tn.read_some()
    rex = r'incorrect'
    tmp = re.search(rex,str(result))
    if not tmp == None:
        print("密码错误")
        Errlog(ip,"账户或者密码错误")
    for k in range(6):
        tn.write(b"\n")
        time.sleep(1)
    b = 0
    for i in commands:
        comm = i + "\n"
        b +=1
        time.sleep(0.5)
        view_bar(b,len(commands))
        tn.write(str.encode(comm))
    for k in range(20):
        tn.write(b"\n")
    tn.write(b"exit\n")
    data = tn.read_all().decode('utf-8')
    #print (data)
    Log(ip,data)